import os

from pptx import Presentation
from docx import Document
from flask import request
import re
import logging


def extract_ppt_titles(input_ppt):
    try:
        # 加载PPT文件
        prs = Presentation(input_ppt)

        # 创建Word文档
        doc = Document()

        # 遍历每一页PPT
        for slide in prs.slides:

            # 获取标题
            title_shape = slide.shapes.title
            if title_shape and title_shape.has_text_frame:
                title = title_shape.text_frame.text
            else:
                title = "未获取到标题"  # 如果标题为空，设置为"未获取到标题"
            doc.add_heading(title, level=1)  # 使用一级标题添加标题到Word文档

            # 获取正文
            text = []
            for shape in slide.shapes:
                if shape.has_text_frame:
                    for paragraph in shape.text_frame.paragraphs:
                        text.append(paragraph.text)

            # 查找关键词
            keywords = re.findall(r'\w{4,}', ' '.join(text))
            # doc.add_paragraph(' '.join(keywords))  # 将关键词添加到Word文档
            doc.add_paragraph("正文关键词：" + ' '.join(text))  # 将关键词添加到Word文档


            # 获取备注
            notes_slide = slide.notes_slide
            notes_text = notes_slide.notes_text_frame.text
            if notes_text:
                doc.add_paragraph("原备注：" + notes_text)

        # 构建输出文件路径
        # output_dir = os.path.dirname(input_ppt)  # 输入PPT的目录
        filename = os.path.splitext(os.path.basename(input_ppt))[0]
        # output_filename = os.path.join(output_dir, filename + ".docx")
        # fileout = file_path_root + filename + ".docx"
        # fileout = os.getcwd() + filename + ".docx"

        fileout = os.path.join(os.getcwd(), filename + ".docx")
        # 保存Word文档
        doc.save(fileout)

        return filename +".docx"  # 返回输出文件路径

    except Exception as e:
        logging.exception(e)
        return "文件解析失败，请检查文件格式是否正确！"
        

if __name__ == '__main__':
      extract_ppt_titles("人工智能.pptx")
        